<?php

//封装一个数据库操作类


class  db {
	
	public $pdo;//$this->pdo;
	public $host='localhost';
	public $port=3306;
	public $dbname='test';
	public $user='root';
	public $pass='root';
	/*
	$config = array(
		'host'=>'',
		'port'=>'',
		'dbname'=>'',
		'user'=>'',
		'pass'=>'',
	)
	
	**/
	function __construct($config){
		
		$this->host = $config['host'];
		$this->port = $config['port'];
		$this->dbname = $config['dbname'];
		$this->user = $config['user'];
		$this->pass = $config['pass'];
		
		$this->connect_db();
	}
	
	function connect_db(){
		
		try {  
			$pdo = new PDO('mysql:host='.$this->host.';port='.$this->port.';dbname='.$this->dbname, $this->user, $this->pass);  
			//没有设置编码，最好下面执行一句设置编码
			$pdo->exec('set names utf8');
			
			$this->pdo = $pdo;
			
			
		} catch (PDOException $e) {  
			print "Error!: " . $e->getMessage() . "<br/>";  //exit echo 
			die();  
		}
		
	}
	//插入数据
	function add($sql){
		$res = $this->pdo->exec($sql);
		if($res){
			//echo '添加成功,数据ID为：'.$pdo->lastinsertid().'<br/>';
			return $this->pdo->lastinsertid();
		}else{
			//echo '添加失败！'
			$this->error();
			return false;
		}
		
		
	}
	
	//查询数据
	function find($sql){
		$res = $this->pdo->query($sql); 
		$data = [];
		while($row = $res->fetch(PDO::FETCH_ASSOC)){
			$data[] = $row;
		}
		return $data;
		
	}
	
	//更新数据
	function update($sql){
		$res = $this->pdo->exec($sql);
		if($res){
			//echo '更新数据成功，更新数据条数：'.$res->rowCount().'<br/>';
			return $res;//true
		}else{
			//$this->error();
			//echo '更新失败！';
			return false;
		}
		
	}
	
	//删除数据
	function del($sql){
		$res = $this->pdo->exec($sql);
		if($res){
			//echo '删除数据成功<br/>';
			return $res;
		}else{
			//$this->error();
			return false;
		}
		
		
		
	}
	
	//错误输出
	function error(){
		
		$error = $this->pdo->errorInfo();
		var_dump($error);exit;
		
	}
	
}




